package com.wangzeqi.changliaoba.worldlet.circle;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;

import com.easemob.chat.EMChatManager;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.cache.memory.impl.UsingFreqLimitedMemoryCache;
import com.nostra13.universalimageloader.cache.memory.impl.WeakMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.nostra13.universalimageloader.core.download.BaseImageDownloader;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.parse.ParseException;
import com.parse.ParseFile;
import com.parse.ParseObject;
import com.parse.SaveCallback;
import com.wangzeqi.BmobEntity.FriendCircleText;
import com.wangzeqi.cache.AllLruCacheLoad;
import com.wangzeqi.changliaba.dao.FriendCircle;
import com.wangzeqi.changliaoba.R;
import com.wangzeqi.changliaoba.base.BaseActivity;
import com.wangzeqi.changliaoba.util.OSUtils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.ArrayList;

import cn.bmob.v3.BmobObject;
import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.listener.SaveListener;

/**
 * Created by dllo on 16/3/7.
 */
public class FriendCircleSendActivity extends BaseActivity implements View.OnClickListener {

    private Button sendBtn;
    private EditText editText;
    private ImageButton imageButton;
    private static final int REQUEST_PICK = 0;
    private GridView gridview;
    private GridAdapter adapter;
    private ArrayList<String> selectedPicture = new ArrayList<String>();
    private String ADDPIC = "add";
    private DisplayImageOptions options;
    private LayoutInflater inflater;

    String url= null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.friend_send_message_text_layout);
        sendBtn = (Button) findViewById(R.id.send_message_circle);
        sendBtn.setOnClickListener(this);
        editText = (EditText) findViewById(R.id.msg_et);
        editText.addTextChangedListener(new EditChangedListener());
        imageButton = (ImageButton) findViewById(R.id.back_btn);
        imageButton.setOnClickListener(this);

        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
                this)
                .threadPriority(Thread.NORM_PRIORITY - 2)
                .memoryCache(new WeakMemoryCache())
                .denyCacheImageMultipleSizesInMemory()
                .discCacheFileNameGenerator(new Md5FileNameGenerator())
                .tasksProcessingOrder(QueueProcessingType.LIFO)
                .imageDownloader(new BaseImageDownloader(this, 10000, 60000))
                .memoryCache(new UsingFreqLimitedMemoryCache(2 * 1024 * 1024))
                .discCacheFileCount(100) // 缓存的文件数量
                .build();
        ImageLoader.getInstance().init(config);
        options = new DisplayImageOptions.Builder()
                .resetViewBeforeLoading(true).cacheOnDisc(true)
                .imageScaleType(ImageScaleType.EXACTLY).cacheInMemory(true)
                        // 设置下载的图片是否缓存在内存中
                .cacheOnDisc(true)
                        // 设置下载的图片是否缓存在SD卡中
                .bitmapConfig(Bitmap.Config.RGB_565)
                .displayer(new FadeInBitmapDisplayer(300)).build();
        selectedPicture.add(ADDPIC);
        gridview = (GridView) findViewById(R.id.gridview);
        adapter = new GridAdapter();
        gridview.setAdapter(adapter);
        inflater = LayoutInflater.from(this);
        gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String temp = selectedPicture.get(position);
                if (temp.equals(ADDPIC)) {
                    Intent intent = new Intent(FriendCircleSendActivity.this, SelectPictureActivity.class);
                    int max = 9 - selectedPicture.size() + 1;
                    intent.putExtra(
                            SelectPictureActivity.INTENT_MAX_NUM,
                            max);
                    startActivityForResult(intent, REQUEST_PICK);
                }
            }
        });
        gridview.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                String temp = selectedPicture.get(position);
                if (!temp.equals(ADDPIC)) {
                    dialog(position);
                }
                return false;
            }
        });
    }

    public void dialog(final int index) {
        AlertDialog.Builder builder = new AlertDialog.Builder(FriendCircleSendActivity.this);
        builder.setMessage("确认删除么？");
        builder.setTitle("提示");
        builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                selectedPicture.remove(index);
                if (selectedPicture.size() < 9 && !selectedPicture.contains(ADDPIC)) {
                    selectedPicture.add(ADDPIC);
                }
                adapter.notifyDataSetChanged();
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.create().show();
    }

    public void selectedPicture(View view) {
        startActivityForResult(new Intent(this, SelectPictureActivity.class), REQUEST_PICK);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.send_message_circle:
                sendMsg();
                break;

            case R.id.back_btn:
                finish();
                break;
        }
    }

    private void sendMsg() {
        AllLruCacheLoad cacheLoad = new AllLruCacheLoad();
        BmobFile file = new BmobFile();

        Log.e("FriendCircleSendActivit---->>>", "file--->>>" +file);
        FriendCircleText obj = new FriendCircleText();
        String name = EMChatManager.getInstance().getCurrentUser();
        obj.setUsername(name);
        obj.setText(editText.getText().toString().trim());
        obj.setLike_count(0);
//        obj.setPicture(file);
        obj.save(this, new SaveListener() {
            @Override
            public void onSuccess() {
                Toast.makeText(FriendCircleSendActivity.this, "发送成功", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFailure(int i, String s) {
                Toast.makeText(FriendCircleSendActivity.this, "发送失败"+s, Toast.LENGTH_SHORT).show();
                Log.e("FriendCircleSendActivit", "发送失败--->>>" + s);
            }
        });
        finish();
//        ParseObject po = new ParseObject("Friends");
//        ParseQuery<ParseObject> pq = ParseQuery.getQuery("");
//        pq.getFirstInBackground(new GetCallback<ParseObject>() {
//            @Override
//            public void done(ParseObject object, ParseException e) {
//                ParseFile file = object.getParseFile("");
//                file.getDataInBackground(new GetDataCallback() {
//                    @Override
//                    public void done(byte[] data, ParseException e) {
//                        Bitmap bitmap1 = BitmapFactory.decodeByteArray(data, 0, data);
//                        imageView.setImageBitmap(bitmap1);
//                    }
//                });
//            }
//
//        });
//        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.chat_logo);
//        ByteArrayOutputStream stream = new ByteArrayOutputStream();
//        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
//        byte[] datass = stream.toByteArray();
//        final ParseFile imgeFile = new ParseFile("image.jpg", datass);
//        imgeFile.saveInBackground();
//        po.put("friend_icon", imgeFile);
//        po.put("friend_id", "1111");
//        po.put("friend_nickname", "畅聊吧主");
//        //存取回调
//        po.saveInBackground(new SaveCallback() {
//            @Override
//            public void done(ParseException e) {
//            }
//        });

    }


    private class EditChangedListener implements TextWatcher {
        private CharSequence temp;

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            temp = s;
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {


            String name = editText.getText().toString().trim();
            if (name.length() > 0) {
                sendBtn.setClickable(true);
                sendBtn.setTextColor(Color.WHITE);
            } else {
                sendBtn.setClickable(false);
                sendBtn.setTextColor(Color.GRAY);
            }
        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    }

    /**
     * J2SE 提供的最后一个批注是 @SuppressWarnings。
     * 该批注的作用是给编译器一条指令，告诉它对被批注的代码元素内部的某些警告保持静默。
     * unchecked 执行了未检查的转换时的警告，例如当使用集合时没有用泛型 (Generics) 来指定集合保存的类型。
     */

    @SuppressWarnings("unchecked")
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            ArrayList<String> temp = (ArrayList<String>) data
                    .getSerializableExtra(SelectPictureActivity.INTENT_SELECTED_PICTURE);
            selectedPicture.addAll(selectedPicture.size() - 1, temp);
            if (selectedPicture.size() > 9) {
                selectedPicture.remove(ADDPIC);
            }
            adapter.notifyDataSetChanged();
        }
    }

    class GridAdapter extends BaseAdapter {
//        ViewGroup.LayoutParams params = new AbsListView.LayoutParams(
//                ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);

        AllLruCacheLoad cache = new AllLruCacheLoad();
        @Override
        public int getCount() {
            return selectedPicture.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            convertView = inflater.inflate(R.layout.item_p, null);
            ImageView iv = (ImageView) convertView.findViewById(R.id.iv_pic);
            String path = selectedPicture.get(position);
            if (!TextUtils.isEmpty(path) && path.equals(ADDPIC)) {
                iv.setImageResource(R.mipmap.icon_addpic_unfocused);
            } else {
                ImageLoader.getInstance().displayImage("file://" + path, iv, options, new ImageLoadingListener() {
                    @Override
                    public void onLoadingStarted(String imageUri, View view) {

                    }

                    @Override
                    public void onLoadingFailed(String imageUri, View view, FailReason failReason) {

                    }

                    @Override
                    public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
                        cache.putBitmap(imageUri,loadedImage);
                        url = imageUri;
                    }

                    @Override
                    public void onLoadingCancelled(String imageUri, View view) {

                    }
                });
            }
            return convertView;
        }

    }
}
